package formvalidate

import (
	"errors"
	"regexp"

	"gitee.com/yookie316/goutils/timex"
	valid "github.com/asaskevich/govalidator"
)

const mobileReg = `^1[2-9]\d{9}$`

func init() {
	valid.SetFieldsRequiredByDefault(true)

	valid.CustomTypeTagMap.Set("date", func(i, o interface{}) bool {
		_, err := timex.ParseShortCSTInLocation(i.(string))
		return err == nil
	})

	valid.CustomTypeTagMap.Set("mobile", func(i, o interface{}) bool {
		phone := i.(string)
		mobileR := regexp.MustCompile(mobileReg)
		return mobileR.Match([]byte(phone))
	})
}

func IsDateOrEmpty(v string) bool {
	if v == "" {
		return true
	}
	return valid.IsTime(v, timex.CSTLayoutShort)
}

func ValidateMapData(v, rules map[string]interface{}) (bool, error) {
	_, err := valid.ValidateMap(v, rules)
	if err != nil {
		errs := err.(valid.Errors).Errors()
		return false, errors.New(errs[0].Error())
	}
	return true, nil
}

func ValidateStruct(v interface{}) (bool, error) {
	_, err := valid.ValidateStruct(v)
	if err != nil {
		errs := err.(valid.Errors).Errors()
		return false, errors.New(errs[0].Error())
	}
	return true, nil
}
